<!-- 批次-->
<template>
  <MainSlot v-loading="loading">
    <!-- <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template> -->
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <div class="custom-tree-container">
        <el-tree :data="treeData" node-key="batchId" :props="defaultProps" @node-click="handleNodeClick"
          :default-expanded-keys="expaAndList">
          <span class="custom-tree-node " slot-scope="{ node, data }">
            <span>
              <i :class="data.child && data.child.length > 0 ? 'el-icon-folder-opened' : 'el-icon-document'"></i>
              <span class="label itemData batchName">{{ node.label }}</span>
              <span class="itemData" v-show="data.batchType == 'MANAGEMENT'"> <span class="label">批次类型：</span>
                管理批次</span>
              <span class="itemData" v-show="data.batchType == 'PRODUCTION'"> <span class="label">批次类型：</span>
                生产批次</span>
              <span class="itemData" v-show="data.batchType == 'BREEDING'"> <span class="label">批次类型：</span> 养殖批次</span>
              <span class="itemData"> <span class="label">批次号：</span> {{ data.batchCode }}</span>
              <span class="itemData"> <span class="label">创建日期：</span> {{ $moment(data.buildDate).format("YYYY-MM-DD")
                }}</span>
              <span class="itemData" :class="data.status == 'COMPLETED' ? 'COMPLETED' : 'NOCOMPLETED'"> <span
                  class="label">批次完成状态：</span> {{ data.status == 'COMPLETED' ? '已完成' : '未完成' }}</span>
            </span>
            <span>
              <el-button v-show="codeList.indexOf('edit') !== -1" type="warning" icon="el-icon-edit-outline"
                :disabled="data.status == 'COMPLETED'" plain @click.stop="() => editPond(data, node.level)">
                编 辑
              </el-button>
              <template v-show="data.batchType !== 'BREEDING' && codeList.indexOf('add') !== -1">
                <el-button :disabled="data.status == 'COMPLETED'" v-show="data.batchType == 'MANAGEMENT'"
                  icon="el-icon-circle-plus-outline" type="primary" plain
                  @click.stop="() => addPondBatch({ ...data, batchType: 'PRODUCTION' }, node.level)">
                  添加生产批次
                </el-button>
                <el-button :disabled="data.status == 'COMPLETED'" v-show="data.batchType == 'MANAGEMENT'"
                  icon="el-icon-circle-plus-outline" type="primary" plain
                  @click.stop="() => addPondBatch({ ...data, batchType: 'BREEDING' }, node.level)">
                  添加养殖批次
                </el-button>
                <el-button :disabled="data.status == 'COMPLETED'" v-show="data.batchType == 'PRODUCTION'"
                  icon="el-icon-circle-plus-outline" type="primary" plain
                  @click.stop="() => addPondBatch({ ...data, batchType: 'BREEDING' }, node.level)">
                  添加养殖批次
                </el-button>
              </template>
              <el-button v-show="codeList.indexOf('delete') !== -1" type="danger" icon="el-icon-delete" plain
                @click.stop="() => delList([data])">
                删 除
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size"  @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <!-- 管理 -->
      <AddEdit :title="'管理批次'" :parentId="parentId" :batchType="batchType" :facilityList="facilityList"
        :varietyList="varietyList" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
      <!-- 生产 -->
      <AddEditProduction :title="'生产批次'" :parentId="parentId" :batchType="batchType" :facilityList="facilityList"
        :varietyList="varietyList" @closeDialog="closeDialog" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible_Production" :data="formData">
      </AddEditProduction>
      <!-- 养殖 -->
      <AddEditBreeding :title="'养殖批次'" :parentId="parentId" :batchType="batchType" :facilityList="facilityList"
        :varietyList="varietyList" @closeDialog="closeDialog" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible_Breeding" :data="formData">
      </AddEditBreeding>
      <BatchInfo :title="'管理批次基础信息'" :dialogVisible="isViewBatchInfo" @closeDialog="closeDialog" />
      <BatchInfoProduction :title="'生产批次基础信息'" :dialogVisible="isViewBatchInfoProduction" @closeDialog="closeDialog" />
      <BatchInfoBreeding :title="'养殖批次基础信息'" :dialogVisible="isViewBatchInfoBreeding" @closeDialog="closeDialog" />
    </template>
  </MainSlot>
</template>
<script>
import { mapGetters } from 'vuex'
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
// 添加批次
import AddEdit from './components/addEdit.vue';
import AddEditBreeding from './components/addEditBreeding.vue';
import AddEditProduction from './components/addEditProduction.vue';
// 批次信息
import BatchInfo from './components/batchInfo.vue';
import BatchInfoBreeding from './components/batchInfoBreeding.vue';
import BatchInfoProduction from './components/batchInfoProduction.vue';

import batch from '@/api/batch/batchManagement';
import varietyManagement from '@/api/basicInformation/varietyManagement';
import facilityManagement from '@/api/digtalOperation/facilityManagement';

export default {
  components: { MainSlot, Pagination, BtnSlot, EnumSlot, BatchInfo, BatchInfoBreeding, BatchInfoProduction, AddEdit, AddEditBreeding, AddEditProduction },
  data() {
    return {
      pondStatus: {
        CREATE: '新创建',
        WEIGHED: '已称重',
        PUT_POND: '已投塘',
        SEALED_POND: '已封塘',
        COMPLETED: '已完成'
      },
      title: '管理批次',
      loading: false,
      addEditFlag: 'add',
      dialogVisible: false,
      dialogVisible_Production: false,
      dialogVisible_Breeding: false,
      isViewBatchInfo: false,
      isViewBatchInfoProduction: false,
      isViewBatchInfoBreeding: false,
      formData: {},
      expaAndList: [],
      page: 1,
      size:10,
      selectIndex: 0,
      total: 10,
      parentId: '',
      batchType: '',
      btnList: ['add_gl', 'add_sc', 'add_yz'],
      id: 1000,
      searchFormData: {},
      varietyList: [],
      facilityList: [],
      treeData: [],
      defaultProps: {
        children: 'child',
        label: 'batchName'
      }
    }
  },

  computed: {
    ...mapGetters([
      'codeList'
    ]),
    densityUnitType() {
      return this.$store.state.initData.enum.status
    }
  },
  mounted() {
    this.initData();
    this.queryPageByCondition();
  },
  methods: {
    handleNodeClick(data) {
      this.expaAndList.push(data.batchId)
    },
    async initData() {
      //获取品种；
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
    },
    queryPageByCondition() {
      console.log(this.searchFormData)
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData
        }
      };
      batch.queryTreePageByCondition(params).then(res => {
        if (res.code == 1) {
          this.treeData = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      });
    },
    delList(deleteList = [], key = 'batchId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      if (list.length == 0) return
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await batch.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag.indexOf('add') != -1) {
        this.formData = {};
        this.addEditFlag = 'add';
      }
      switch (flag) {
        case 'add_gl':
          this.dialogVisible = true;
          this.batchType = 'MANAGEMENT';
          this.title = '管理批次';
          break;
        case 'add_sc':
          this.dialogVisible_Production = true;
          this.batchType = 'PRODUCTION';
          this.title = '生产批次';
          break;
        case 'add_yz':
          this.dialogVisible_Breeding = true;
          this.batchType = 'BREEDING';
          this.title = '养殖批次';
          break;
        default:
          this.batchType = '';
          this.dialogVisible = false;
          this.dialogVisible_Production = false;
          this.dialogVisible_Breeding = false;
          break;
      }
    },

    lookOver(data, level) {
      console.log(data, level)
      if (level == 1) this.isViewBatchInfo = true;
      if (level == 2) this.isViewBatchInfoProduction = true;
      if (level == 3) this.isViewBatchInfoBreeding = true;
    },
    addPondBatch(data, level) {
      if (data.status == 'COMPLETED') {
        this.$message.warning('该批次已完成')
        return
      }
      this.parentId = data.batchId;
      this.batchType = data.batchType;
      this.addEditFlag = 'add';
      this.formData = {};
      this.facilityList = this.facilityList.filter(item => {
        return Number(item.facilityId) == Number(data.facilityId);
      });
      if (this.batchType == 'PRODUCTION') this.dialogVisible_Production = true;
      if (this.batchType == 'BREEDING') this.dialogVisible_Breeding = true;
    },
    editPond(data, level) {
      console.log('父级id', data.parentId)
      if (data.status == 'COMPLETED') {
        this.$message.warning('该批次已完成')
        return
      }
      this.parentId = data.parentId;
      this.batchType = data.batchType;
      this.addEditFlag = 'edit';
      this.formData = JSON.parse(JSON.stringify(data))
      if (this.batchType == 'MANAGEMENT') this.dialogVisible = true;
      if (this.batchType == 'PRODUCTION') this.dialogVisible_Production = true;
      if (this.batchType == 'BREEDING') this.dialogVisible_Breeding = true;
      console.log(data, level)
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.dialogVisible_Production = false;
      this.dialogVisible_Breeding = false;
      this.isViewBatchInfo = false;
      this.isViewBatchInfoBreeding = false;
      this.isViewBatchInfoProduction = false;
      this.parentId = null;
      this.batchType = null;
      this.formData = {};
      this.queryPageByCondition();
      this.initData();
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 50px;
  border-bottom: 1px solid #f0f0f0;
}

.custom-tree-container {
  width: 100%;

  .icon {
    font-size: 14px;
  }
}

::v-deep .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.label {
  color: #333333 !important;
}


.itemData {
  padding: 0 15px;
  display: inline-block;
  min-width: 150px;
  font-size: 14px;
  color: #999999;
  text-align: left;
}

.batchName {
  width: 180px;
  overflow: hidden;
  /* 隐藏超出部分 */
  white-space: nowrap;
  /* 防止文本换行 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
}

.COMPLETED {
  color: rgb(26, 189, 107);
}
</style>